package cn.walls1717.juc.future;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

/**
 * applyToEither方法的使用
 *
 * @author walls1717
 * @create 2022/12/09 17:02
 **/
@Slf4j
public class CompletableFutureFastDemo {

    public static void main(String[] args) {
        CompletableFuture<String> futureA = CompletableFuture.supplyAsync(() -> {
            log.info("A start");
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "A";
        });

        CompletableFuture<String> futureB = CompletableFuture.supplyAsync(() -> {
            log.info("B start");
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "B";
        });

        // A.applyToEither(B, f) 判断A与B那个先执行完成，先执行完成的f就是谁的返回值。
        CompletableFuture<String> result = futureA.applyToEither(futureB, f -> {
            return f + " is winner";
        });

        log.info(result.join());
    }
}
